<template>
  <div>
    <!-- 面包屑区域-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示框 -->
      <el-alert title="只允许选择3级分类！" type="warning" show-icon>
      </el-alert>
      <!-- 级联选择器 -->
      <el-row class="dt">
        <el-col>
          <span>请选择分类：</span>
          <el-cascader
            v-model="selectCatKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- Tabs 页签 -->
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" :border="true" stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- tag区 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  :closable="true"
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 切换的文本框 -->
                <el-input
                  class="input-new-tag el-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>

                <!-- 添加tag 按钮 -->
                <el-button
                  v-else
                  class="button-new-tag el-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column label="#" type="index"> </el-table-column>
            <!-- 参数名称列 -->
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <!-- 操作列 -->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" :border="true" stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- tag区 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  :closable="true"
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 切换的文本框 -->
                <el-input
                  class="input-new-tag el-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>

                <!-- 添加tag 按钮 -->
                <el-button
                  v-else
                  class="button-new-tag el-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column label="#" type="index"> </el-table-column>
            <!-- 属性名称列 -->
            <el-table-column label="属性名称" prop="attr_name">
            </el-table-column>
            <!-- 操作列 -->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数/属性的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 添加表单 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="100px"
        :rules="addFormRules"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数的对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!-- 编辑表单 -->
      <el-form
        ref="editFormRef"
        :model="editForm"
        label-width="100px"
        :rules="editFormRules"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Params",
  data() {
    return {
      selectCatKeys: [],
      cateList: [],
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 页签的默认激活属性
      activeName: "many",
      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],
      // 控制添加对话框的布尔值
      addDialogVisible: false,
      // 添加表单数据
      addForm: {
        attr_name: "",
      },
      addFormRules: {
        attr_name: [{ required: true, message: "请输入参数", trigger: "blur" }],
      },
      // 控制编辑对话框的布尔值
      editDialogVisible: false,
      // 编辑表单数据
      editForm: {
        attr_name: "",
      },
      editFormRules: {
        attr_name: [{ required: true, message: "请输入参数", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getCateList();
  },
  // 计算属性
  computed: {
    // 按钮被禁用返 true
    isBtnDisable() {
      if (this.selectCatKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // 获取cateId
    cateId() {
      if (this.selectCatKeys.length == 3) {
        return this.selectCatKeys[2];
      }
      return null;
    },
    // 对话框文本标题
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },

  methods: {
    // 获取分类数据
    async getCateList() {
      const { data: res } = await this.$axios.get("categories");
      // 获取失败
      if (res.meta.status !== 200) {
        this.$message.error("获取数据失败！");
      }
      // 获取成功
      this.cateList = res.data;
    },
    // 级联选择框中项变化，会触发这个函数
    handleChange() {
      // 证明不是三级分类
      if (this.selectCatKeys.length !== 3) {
        this.selectCatKeys = []
        this.manyTableData=[]
        this.onlyTableData=[]
        return;
      }
      // 是三级分类
      this.getParamsList();
    },
    // 切换Tabs页签
    handleTabsClick() {
      // console.log(this.activeName);
      this.getParamsList();
    },

    // 获取参数数据
    async getParamsList() {
    // 证明选中的是三级分类
      const { data: res } = await this.$axios.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      );

      if (res.meta.status !== 200) {
        this.$message.error("数据请求失败");
      }
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 控制文本框的显示布尔值
        item.inputVisible = false;
        item.inputValue = "";
      });

      if (this.activeName == "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
    },
    // 监听对话框的关闭事件
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        const { data: res } = await this.$axios.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 201) {
          this.$message.error("添加参数失败！");
        }
        this.$message.success("添加属性成功！");
        this.addDialogVisible = false;
        this.getParamsList();
      });
    },

    // 点击按钮展示修改的是对话框
    async showEditDialog(attr_id) {
      // 查询当前参数的信息
      const { data: res } = await this.$axios.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error("获取参数信息失败");
      }
      // console.log(res);
      this.editForm = res.data;

      this.editDialogVisible = true;
    },
    // 监听编辑对话框的关闭事件
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    // 点击按钮修复参数信息
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$axios.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改参数失败！");
        }
        this.$message.success("修改参数成功！");
        this.getParamsList();
        this.editDialogVisible = false;
      });
    },
    // 点击删除参数
    async removeParams(attr_id) {
      // 弹窗提示是否需要删除
      const result = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (result !== "confirm") {
        return this.$message.info("已取消删除操作");
      }
      // 发起删除请求
      const { data: res } = await this.$axios.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      );
      if (res.meta.status !== 200) {
        this.$message.error("删除参数失败！");
      }
      this.$message.success("删除参数成功！");
      this.getParamsList();
    },
    // 点击tag按钮添加
    showInput(row) {
      row.inputVisible = true;
      // 文本款自动获得焦点
      // $nextTick 页面重新渲染时调用里面的回调函数
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 回车或者失去焦点时触发的事件
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      // 输入的inputValue是有效值
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      this.saveAttrVals(row)
    },
    // 把attr_vals的操作 保存到数据库
    async saveAttrVals(row) {
      // 给attr_vals添加新的数据
      const { data: res } = await this.$axios.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error("修改参数项失败！");
      }
      this.$message.success("修改参数项成功！");
      row.inputVisible = false;
    },
    // 关闭tag标签 移除参数项
    handleClose(i, row) {
      // 数组删除一项
      row.attr_vals.splice(i,1)
      this.saveAttrVals(row)

    },
  },
};
</script>

<style lang="less" scoped>
.dt {
  margin-top: 15px;
  margin-bottom: 10px;
}
.el-tag {
  margin-left: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
